import { fileURLToPath, URL } from 'node:url'
import WindiCSS from 'vite-plugin-windicss'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from '@vant/auto-import-resolver'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { wrapperEnv } from './build/utils'
import autoprefixer from "autoprefixer";
import postCssPxToRem from "postcss-pxtorem"
import { defineConfig, loadEnv } from 'vite'
import Icons from 'unplugin-icons/vite'

export default ({ mode }) => {
  const env = loadEnv(mode, process.cwd())

  const viteEnv = wrapperEnv(env)
  const { VITE_PORT } = viteEnv
  return defineConfig({
    base: '.',
    plugins: [
      vue(),
      WindiCSS(),
      Icons(),
      AutoImport({
        resolvers: [ElementPlusResolver({ importStyle: 'sass' }), VantResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver({ importStyle: 'sass' }), VantResolver()],
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    server: {
      host: true,
      port: VITE_PORT,
      proxy: {
        // 接口地址代理
        [env.VITE_API_BASE_URL]: {
          target: env.VITE_BASE_API_ORIGIN, // 接口的域名
          // secure: false, // 如果是https接口，需要配置这个参数
          changeOrigin: true, // 如果接口跨域，需要进行这个参数配置
          rewrite: (path) => {
            return path.replace(env.VITE_API_BASE_URL, '')
          },
        },
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/assets/scss/elementPlus.scss" as *;`,
        },
      },
      postcss: {
        plugins: [
          autoprefixer({
            overrideBrowserslist: [
              "Android 4.1",
              "iOS 7.1",
              "Chrome > 31",
              "ff > 31",
              "ie >= 8",
            ],
          }),
          postCssPxToRem({
            // 自适应，px>rem转换
            rootValue: 37.5, // 75表示750设计稿，37.5表示375设计稿
            propList: ["*"], // 需要转换的属性，这里选择全部都进行转换 也可以'font', 'font-size', 'line-height', 'letter-spacing'等
            selectorBlackList: [".van"], // 过滤掉van-开头的class，不进行rem转换
            exclude: "/node_modules", // 忽略包文件转换rem
          }),
        ],
      },
    },
  })
}
